//////////////////////////////////////////////////////////////////////////
// $Id: VertexBuffer.cpp,v 1.1 2009/04/03 12:46:11 sunjun Exp $
//////////////////////////////////////////////////////////////////////////

#include "Local.h"

//////////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////////

NAMESPACE_BEGIN

//////////////////////////////////////////////////////////////////////////	

	VertexBuffer::VertexBuffer( const Context* rc ) : mHandle(NULL)
	{
		CHECK(rc);
		mRCPtr = (Context*)rc;
	}

	VertexBuffer::~VertexBuffer() 
	{
		if((IDirect3DVertexBuffer9*)mHandle){((IDirect3DVertexBuffer9*)mHandle)->Release(); mHandle = NULL;}
	}

	//////////////////////////////////////////////////////////////////////////

	/*
	====================
	handle
	====================
	*/
	INLINE HANDLE VertexBuffer::handle() const
	{
		return mHandle;
	}

	/*
	====================
	load
	====================
	*/
	INLINE VOID VertexBuffer::load( const VOID* data, U32 size, U32 stride )
	{
		// create the vertex buffer
		if( mHandle == NULL )
		{
			IDirect3DVertexBuffer9* d3d9VertexBuffer = NULL;
			HRESULT hr = ((IDirect3DDevice9*)mRCPtr->handle())->CreateVertexBuffer( size, D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, &d3d9VertexBuffer, NULL );
			if(FAILED(hr)) MAssert(VA("VertexBuffer::load : create the vertex buffer is failed(%s)!", DXGetErrorDescription(hr)));
			mHandle = d3d9VertexBuffer;
		}
		
		// load the vertex buffer
		if( data )
		{
			VOID *dest;
			HRESULT hr = ((IDirect3DVertexBuffer9*)mHandle)->Lock(0, size, &dest, 0);
			if( SUCCEEDED(hr) )
			{
				::memcpy(dest, data, size);
				((IDirect3DVertexBuffer9*)mHandle)->Unlock();
			} 
			else 
			{
				MAssert(VA("VertexBuffer::load : lock the vertex buffer is failed(%s)!", DXGetErrorDescription(hr)));
			}
		}

		// store the stride
		mStride = stride;
	}	

//////////////////////////////////////////////////////////////////////////

NAMESPACE_END

//////////////////////////////////////////////////////////////////////////
